Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

541
Views
error_code":403,"description":"Prohibido: el bot fue bloqueado por el usuario. manejador de error en python

Tengo un problema al usar la API de telebot en python. Si el usuario envía un mensaje al bot y espera la respuesta y al mismo tiempo bloquea el bot. Recibo este error y el bot no responderá para otros usuarios:

403,"description":"Prohibido: el bot fue bloqueado por el usuario

Intente, catch block no está manejando este error por mí

¿alguna otra idea para salir de esta situación? ¿Cómo saber que el bot está bloqueado por el usuario y evitar responder a este mensaje?

este es mi código:

 import telebot import time @tb.message_handler(func=lambda m: True) def echo_all(message): try: time.sleep(20) # to make delay ret_msg=tb.reply_to(message, "response message") print(ret_msg) assert ret_msg.content_type == 'text' except TelegramResponseException as e: print(e) # do not handle error #403 except Exception as e: print(e) # do not handle error #403 except AssertionError: print( "!!!!!!! user has been blocked !!!!!!!" ) # do not handle error #403 tb.polling(none_stop=True, timeout=123)
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Esto no parece ser realmente un error y, por lo tanto, try catch no podrá manejarlo por usted. Tendrá que obtener el código de retorno y manejarlo con declaraciones if else probablemente (las declaraciones de cambio funcionarían mejor en este caso, pero no creo que Python tenga la sintaxis para ello).

EDITAR

Siguiendo las llamadas al método aquí , parece que reply_to() devuelve send_message() , que devuelve un objeto Message , que contiene una cadena json establecida en self.json en el __init__() . En esa cadena, es probable que pueda encontrar el código de estado (400 y 500 que puede capturar y manejar según lo necesite).

over 4 years ago · Santiago Trujillo Report

0

Puede manejar este tipo de errores de muchas maneras. Seguro que necesita usar try/except en todos los lugares donde cree que se generaría esta excepción.

Entonces, primero, importe la clase de excepción, es decir:

 from telebot.apihelper import ApiTelegramException

Luego, si observa los atributos de esta clase, verá que tiene error_code , description y result_json . La description es, por supuesto, la misma que plantea Telegram cuando te da el error.

Entonces puede volver a escribir su controlador de esta manera:

 @tb.message_handler() # "func=lambda m: True" isn't needed def echo_all(message): time.sleep(20) # to make delay try: ret_msg=tb.reply_to(message, "response message") except ApiTelegramException as e: if e.description == "Forbidden: bot was blocked by the user": print("Attention please! The user {} has blocked the bot. I can't send anything to them".format(message.chat.id))

Otra forma podría ser usar un controlador de excepciones, una función integrada en pyTelegramBotApi. Cuando inicializa su clase de bot con tb = TeleBot(token) , también puede pasar el parámetro controlador de exception_handler .

exception_handler debe ser una clase con el método handle(e: Exception) . Algo como esto:

 class Exception_Handler: def handle(self, e: Exception): # Here you can write anything you want for every type of exceptions if isinstance(e, ApiTelegramException): if e.description == "Forbidden: bot was blocked by the user": # whatever you want tg = TeleBot(token, exception_handler = Exception_Handler()) @tb.message_handler() def echo_all(message): time.sleep(20) # to make delay ret_msg = tb.reply_to(message, "response message")

Déjame saber qué solución usarás. Sobre el segundo, honestamente nunca lo he usado, pero es bastante interesante y lo usaré en mi próximo bot. ¡Deberia de funcionar!

over 4 years ago · Santiago Trujillo Report

0

No ha especificado si el bot está en un grupo o para individuos.
Para mí no hubo problemas con probar y excepto.

Este es mi código:

 @tb.message_handler(func=lambda message: True) def echo_message(message): try: tb.reply_to(message, message.text) except Exception as e: print(e) tb.polling(none_stop=True, timeout=123)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!